package com.example.permission.service.impl;

import com.example.permission.entity.User;
import com.example.permission.mapper.UserMapper;
import com.example.permission.service.UserService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserServiceImpl implements UserService {

    private final SqlSessionFactory sqlSessionFactory;

    public UserServiceImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public User getUserWithRolesByUsername(String username) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.selectUserWithRolesByUsername(username);
        }
    }

    @Override
    public List<User> searchUsersWithDetails(String username, String email, Integer status) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.selectUsersWithRolesAndMenus(username, email, status);
        }
    }

    @Override
    public List<User> getUsersByPage(int page, int pageSize) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            int offset = (page - 1) * pageSize;
            return mapper.selectUsersByPage(offset, pageSize);
        }
    }

    @Override
    public int getUserCount() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            return mapper.countUsers();
        }
    }
}